const Preload = require("./preload");
class Playing extends Preload {
  constructor() {
    super();
    this.MaxNum = 88;
    this.playTimes = 0;
    this.timers = null;
    this.timeTxt = null;
    this.dogs = null;
    this.dogBox = null;
  }
  setBg() {
    let bg = game.add.image(0, 0, "bg_playing")
    bg.width = this.bw;
    bg.height = this.bh;
  }
  setTimer() {
    this.timers = game.add.group();
    this.timers.y = this.setY(70);
    let bg = this.timers.create(0, 0, "bg_heart");
    console.log(this.timers.width / 2);
    let heart = this.timers.create(28, 28, "heart");
    this.timeTxt = game.add.text(84, 14, this.playTimes + "", {
      fontSize: 50,
      fill: "#fff",
      align: "center",
      width: 80
    }, this.timers);
    this.timers.x = this.bw-this.timers.width-40;
    //  this.timeTxt.anchor.setTo(0.5,0);
  }

  setDog() {
    let box = game.add.group();
    this.dogs = box.create(0, 0, "dogs");
    this.dogs.animations.add("rocking", [1, 0, 1, 0, 1, 0], 6);
    this.dogs.animations.play("rocking", true, 1);
    let flag = this.bw / 375;
    box.x = (this.bw / 2) - (box.width / 2) - (30 * flag);
    this.scales(this.dogs, 1);
    box.y = this.bh - this.dogs.height + 20;
    this.pointer = box.create(0, 0, "pointer");
    this.scales(this.pointer);
    this.pointer.x = this.cx / 2 - (this.pointer.width / 2) + 5;
    this.pointer.y = this.dogs.height / 2 - (this.pointer.height / 2) + 40;
    let lFlag = this.pointer.scale.x * 0.8;
    let yFlag = this.pointer.y - 8;
    let tween = game.add.tween(this.pointer.scale).to({
      x: lFlag,
      y: lFlag
    }, 600, null, true, 0, -1);
    let tween1 = game.add.tween(this.pointer).to({
      y: yFlag
    }, 600, null, true, 0, -1);
    tween1.start();
    this.dogs.inputEnabled = true;
    this.dogs.events.onInputDown.add(v => {
      this.clickDog();
    })
    this.dogBox = box;
  }
  setWang() {
    let dy = this.dogBox.y;
    let wang = game.add.image(this.cx, dy+100, "word_wang");
    wang.anchor.setTo(0.5, 0.5);
    wang.scale.set(0.2);
    let step1Top = dy - (110 * (this.bh / 600));
    let step2Top = this.timers.y-50;
    let speed = 400;
    let tween = game.add.tween(wang).to({
      y: step1Top,
      angle: 25,
    }, speed).to({
      y: step2Top,
      angle: -25,
      alpha: 0,
    }, speed).start()
    let tween1 = game.add.tween(wang.scale).to({
      x: 1.3,
      y: 1.3
    }, speed).to({
      x: 1,
      y: 1
    }, speed).start().onComplete.add(function () {
      wang.destroy();
    });
  }
  clickDog() {
    if (this.playTimes >= this.MaxNum) {
      game.state.start("Over");
      return
    }
    this.dogs.animations.play("rocking", true, 1);
    this.playTimes++;
    this.timeTxt.text = this.playTimes;
    this.setWang();
    if (this.pointer) {
      this.pointer.destroy();
    }
  }
  create() {
    this.setBg();
    this.setTimer();
    this.setDog();
  }
}

module.exports = Playing;
